<template>
  <div class="examMgn">
    <GeminiScrollbar class="container" @ready="initScrollbar" :autoshow="true">
      <div class="table-header">
        <p>题库列表</p>
        <div class="search-bar">
          <input v-model="name" type="text" placeholder="试卷标题" @keyup.enter="findPos">
          <div class="btn primary" style="margin-right:5px" @click="findExam">搜索</div>
          <div class="btn primary" @click="addPositionClicked">添加</div>
        </div>
      </div>
      <table class="table">
        <thead>
          <tr>
            <th></th>
            <th>试卷标题</th>
            <th>试题数量</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <template v-for="(pos, index) of tableData">
            <tr :key="pos.id">
              <td class="expend">
                <img
                  :class="{ rotate: nowExpend === index }"
                  @click="expend(index)"
                  src="@/assets/img/u4210.png"/>
              </td>
              <td>{{ pos.name }}</td>
              <td>{{ pos.count }}</td>
              <td>{{ new Date(pos.createDate).Format('yyyy-MM-dd') }}</td>
              <td style="width:105px">
                <a @click="assign(pos.id)">配置</a>
                <a @click="deletePos(pos.id)">删除</a>
              </td>
            </tr>
            <tr :key="pos.id + 10000" v-show="nowExpend === index">
              <td class="middle-container" colspan="8">
                <div class="middle">
                  题库描述：{{ pos.desc }}
                </div>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </GeminiScrollbar>
    <footer>
      <Page @setCurPage="setCurPage" :curPage="curPage" :total="total" :pageSize="pageSize"></Page>
    </footer>
    <position-dialog
      @close="addPositionShow = false"
      @done="addPosition"
      :dialogData="{}"
      title="添加试卷"
      :show="addPositionShow"
    ></position-dialog>
    <position-dialog
      @close="modifyPositionShow = false"
      @done="modifyPosition"
      :dialogData="modifyPositionData"
      title="修改试卷信息"
      :show="modifyPositionShow"
    ></position-dialog>
  </div>
</template>
<script>
/* eslint-disable no-param-reassign */
import Page from '@/components/Pages/index';
import PositionDialog from '@/components/Dialogs/addExam';
import api from '@/api/dbMgn';

async function getExam(curPage, name) {
  const tableData = [];
  const params = new URLSearchParams();
  params.append('name', name);
  params.append('rows', 10);
  params.append('page', curPage);
  const response = await api.getExamApi(params);
  const datas = response.data.rows;
  const total = response.data.total;
  for (let i = 0; i < datas.length; i += 1) {
    tableData.push({
      id: datas[i].businessId,
      name: datas[i].name,
      createDate: datas[i].createDate,
      desc: datas[i].dbType,
      count: datas[i].count,
    })
    ;
  }
  return [total, tableData];
}
export default {
  name: 'examMgn',
  data() {
    return {
      nowExpend: '',
      name: '',
      tableData: [
      ],

      curPage: 1,
      total: 1000,
      pageSize: 10,

      addPositionShow: false,
      modifyPositionShow: false,
      modifyPositionData: null,

      seeShow: false,
      scrollObj: null,
    };
  },
  beforeRouteEnter(to, from, next) {
    if (sessionStorage.getItem('userToken') === null || sessionStorage.getItem('loginType') !== '4') {
      next({ path: '/login' });
    }
    getExam(1, '').then((jobs) => {
      next((vm) => {
        vm.$emit('route-switch', window.location.href.split('/').pop());
        vm.total = jobs[0];
        vm.tableData = [...jobs[1]];
      });
    });
  },
  methods: {
    download(id) {
      window.location.href = `http://123.206.41.36:8080/bexam/getRealPaperWoAu?examId=${id}`;
    },
    async setCurPage(page) {
      this.curPage = page;
      const jobs = await getExam(page, this.name);
      this.total = jobs[0];
      this.tableData = [...jobs[1]];
    },
    expend(index) {
      if (this.nowExpend === index) {
        this.nowExpend = -1;
        return;
      }
      this.nowExpend = index;
      this.$nextTick(() => {
        this.scrollObj.update();
      });
    },
    addPositionClicked() {
      this.addPositionShow = true;
    },
    see() {
      this.seeShow = true;
    },
    addPosition(pos) {
      this.addPositionShow = false;
      const params = new URLSearchParams();
      params.append('name', pos.name);
      params.append('dbType', pos.desc);
      api.addApi(params).then(async (response) => {
        if (response.data.code === 200) {
          this.$alert('添加成功');
          const jobs = await getExam(this.curPage, this.name);
          this.total = jobs[0];
          this.tableData = [...jobs[1]];
        } else {
          this.$alert(response.data.message);
        }
      });
    },
    modifyPositionClicked(pos) {
      this.modifyPositionShow = true;
      this.modifyPositionData = { ...pos };
    },
    modifyPosition(pos) {
      this.modifyPositionShow = false;
      const params = new URLSearchParams();
      params.append('name', pos.name);
      params.append('dbType', pos.desc);
      api.updateApi(pos.id, params).then(async (response) => {
        if (response.data.code === 200) {
          this.$alert('修改成功');
          const jobs = await getExam(this.curPage, this.name);
          this.total = jobs[0];
          this.tableData = [...jobs[1]];
        } else {
          this.$alert(response.data.message);
        }
      });
    },
    changeStatus(posId, status, count) {
      if (count === 0) {
        this.$alert('没有题目的试卷不可被启用');
        return;
      }
      this.$confirm('确定要改变状态吗?', (res) => {
        if (res) {
          const params = new URLSearchParams();
          params.append('status', status);
          api.updateApi(posId, params).then(async (response) => {
            if (response.data.code === 200) {
              this.$alert('修改成功');
              const jobs = await getExam(this.curPage, this.name);
              this.total = jobs[0];
              this.tableData = [...jobs[1]];
            } else {
              this.$alert(response.data.message);
            }
          });
        }
      });
    },
    assign(p) {
      this.$router.push({ name: 'QuestionAssign', query: { dbId: p } });
    },
    deletePos(posId) {
      this.$confirm('确定要删除该试卷吗?', (res) => {
        if (res) {
          api.deleteApi(posId).then(async (response) => {
            if (response.data.code === 200) {
              this.$alert('删除成功');
              const jobs = await getExam(this.curPage, this.name);
              this.total = jobs[0];
              this.tableData = [...jobs[1]];
            } else {
              this.$alert(response.data.message);
            }
          });
        }
      });
    },
    async findExam() {
      const jobs = await getExam(this.curPage, this.name);
      this.total = jobs[0];
      this.tableData = [...jobs[1]];
    },
    initScrollbar(bar) {
      this.scrollObj = bar;
    },
  },
  components: {
    Page,
    PositionDialog,
  },
};
</script>
<style lang="less">
@import url(../../../../static/style/site.comm.less);
@import url(../../../../static/style/site.vars.less);

.examMgn {
  background: #fff;
  box-shadow: 0 3px 6px rgba(6,0,1,.05);
  &>.container {
    position: relative;
    height: 701px;
    overflow-y: scroll;
    &::-webkit-scrollbar {
      display: none;
    }
    .table-header {
      position: sticky;
      top: 0;
    }
    .middle-container {
      box-sizing: border-box;
      padding: 10px;
      padding-left: 40px;
      background: rgb(238, 238, 238);
      height: 100px;
      // display: none;
      .middle {
        text-align: left;
      }
    }
  }
  & > footer {
    padding: 20px 0 20px 0;
    width: 100%;
    background: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
  }
}
</style>
